<template>
  <div class="container mx-auto px-4 py-8 max-w-2xl">
    <header class="text-center mb-8">
      <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-gray-800 mb-2">待办事项列表</h1>
      <p class="text-gray-600">添加、管理和完成你的任务</p>
    </header>

    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
      <AddTodo @add-todo="addTodo" />
    </div>

    <div class="bg-white rounded-lg shadow-md p-6">
      <div class="flex justify-between items-center mb-4">
        <h2 class="text-xl font-semibold text-gray-800">
          任务列表
          <span class="ml-2 text-sm font-normal text-gray-500">({{ remainingCount }} 个待完成)</span>
        </h2>
        <button 
          @click="clearCompleted" 
          class="text-gray-500 hover:text-danger text-sm transition-colors"
          :disabled="completedCount === 0"
          :class="{ 'opacity-50 cursor-not-allowed': completedCount === 0 }"
        >
          <i class="fa fa-trash-o mr-1"></i> 清除已完成
        </button>
      </div>
      
      <TodoList 
        :todos="todos"
        @toggle-todo="toggleTodo"
        @delete-todo="deleteTodo"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import AddTodo from './components/AddTodo.vue';
import TodoList from './components/TodoList.vue';

// 响应式任务列表
const todos = ref([]);

// 从localStorage加载任务
const loadTodos = () => {
  const savedTodos = localStorage.getItem('todos');
  if (savedTodos) {
    todos.value = JSON.parse(savedTodos);
  }
};

// 保存任务到localStorage
const saveTodos = () => {
  localStorage.setItem('todos', JSON.stringify(todos.value));
};

// 页面加载时加载任务
onMounted(loadTodos);

// 添加新任务
const addTodo = (text) => {
  const newTodo = {
    id: Date.now().toString(),
    text,
    completed: false
  };
  
  todos.value.push(newTodo);
  saveTodos();
};

// 切换任务完成状态
const toggleTodo = (id) => {
  const todo = todos.value.find(t => t.id === id);
  if (todo) {
    todo.completed = !todo.completed;
    saveTodos();
  }
};

// 删除任务
const deleteTodo = (id) => {
  todos.value = todos.value.filter(todo => todo.id !== id);
  saveTodos();
};

// 清除已完成任务
const clearCompleted = () => {
  todos.value = todos.value.filter(todo => !todo.completed);
  saveTodos();
};

// 计算属性：已完成任务数量
const completedCount = computed(() => {
  return todos.value.filter(todo => todo.completed).length;
});

// 计算属性：剩余任务数量
const remainingCount = computed(() => {
  return todos.value.length - completedCount.value;
});
</script>

<style>
/* 引入外部资源 */
@import url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css');

/* 基础样式 */
body {
  font-family: 'Inter', system-ui, sans-serif;
  background-color: #f3f4f6;
  min-height: 100vh;
}

/* 自定义颜色变量 */
:root {
  --primary: #3B82F6;
  --danger: #EF4444;
}
</style>
